package com.jctrip.hotel.source.xxl.hworld;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jctrip.hotel.common.constant.XxlJobNameConstant;
import com.jctrip.hotel.common.util.JsonUtil;
import com.jctrip.hotel.domain.dao.HtSourceInfoDao;
import com.jctrip.hotel.domain.entity.HtSourceInfo;
import com.jctrip.hotel.source.model.CommonJobParam;
import com.jctrip.hotel.source.service.hworld.HworldTaskService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: zxy
 * @CreateTime: 2023-09-01 22:21
 * @Description:
 */
@Component
@Slf4j
public class SyncHworldLongerRatesPopXxlJob extends IJobHandler {
    @Resource
    private HworldTaskService hworldTaskService;
    @Resource
    private HtSourceInfoDao htSourceInfoDao;

    @Override
    @XxlJob(XxlJobNameConstant.SYNC_HWORLD_LONGER_RATES_POP)
    public void execute() throws Exception {
        XxlJobHelper.log(XxlJobNameConstant.SYNC_HWORLD_LONGER_RATES_POP + " xxl job start");
        try {
            CommonJobParam hworldJobParam = JsonUtil.toObject(CommonJobParam.class, XxlJobHelper.getJobParam());
            List<HtSourceInfo> htSourceInfos = htSourceInfoDao.selectList(new LambdaQueryWrapper<HtSourceInfo>()
                    .in(HtSourceInfo::getSourceId, hworldJobParam.getSourceIds()));
            if (CollectionUtils.isEmpty(htSourceInfos)) {
                return;
            }
            // todo 目前是多source拉取 ，但是 appId , secret, memberLevel 使用相同，除了rateCode 不同
            String sourceAppId = htSourceInfos.get(0).getSourceAppId();
            String sourceSecret = htSourceInfos.get(0).getSourceSecret();
            String memberLevel = (String) JsonUtil.toMap(htSourceInfos.get(0).getExtra()).get("memberLevel");
            // rateCode : 供应拉取码
            Map<String, String> rateCodeWithSourceIdMap = hworldJobParam.getRateCodes().stream()
                    .collect(Collectors.toMap(CommonJobParam.RateCode::getRateCode, CommonJobParam.RateCode::getSourceId));

            hworldTaskService.syncHworldLongerRatesPop(sourceAppId, sourceSecret, memberLevel,
                    hworldJobParam.getAddDays(), hworldJobParam.getDays(), rateCodeWithSourceIdMap);
        } catch (Exception e) {
            log.error(XxlJobNameConstant.SYNC_HWORLD_LONGER_RATES_POP + "error", e);
        }
        XxlJobHelper.log(XxlJobNameConstant.SYNC_HWORLD_LONGER_RATES_POP + " xxl job start");

    }
}